import {TagInfoWrapper} from '../../components/TagInfoWrapper';
import {Center} from '../../components/Center';
import {ButtonList, DeleteButton, SaveButton} from '../../components/Button';
import React, {useState} from 'react';
import {RecordItemWithId, useRecords} from '../../hooks/useRecords';
import {IconWithName} from '../../components/IconWithName';
import styled from 'styled-components';
import {Editor} from 'components/Editor';
import {useHistory} from 'react-router-dom';
import {getToday} from '../../lib/dayUtils';

type Props = {
  record: RecordItemWithId;
  tagName: string;
}

const NarrowCenter = styled(Center)`
  margin-top: 10px;
  margin-bottom: 10px;
`;

const RecordContent: React.FC<Props> = (props) => {
  const {record, tagName} = props;
  const {updateRecord, deleteRecord} = useRecords();
  const [amount, setAmount] = useState(record.amount?.toString());
  const [createdAt, setCreatedAt] = useState(record.createdAt)
  const [notes, setNotes] = useState(record.notes);
  const history = useHistory();

  const onSave = () => {
    if (parseInt(amount) === record.amount &&  createdAt === record.createdAt && notes === record.notes) return;
    updateRecord(record.id, {amount: parseInt(amount), createdAt ,notes});
    alert('修改成功');
    history.goBack();
  };
  const onDelete = () => {
    if (!window.confirm('确认要删除记录吗？')) return;
    deleteRecord(record.id);
    alert('删除成功');
    history.goBack();
  };
  const cantSave = () => Number(amount) <= 0
  return (
    <>
      <NarrowCenter>
        <IconWithName tagName={tagName} category={record.category}/>
      </NarrowCenter>

      <TagInfoWrapper>
        <Editor label="金额" type="text" placeholder={amount}
                value={amount} onChange={(e) => {setAmount(e.target.value);}}/>
      </TagInfoWrapper>

      <TagInfoWrapper>
        <Editor label="日期" type="date" value={createdAt} max={getToday()}
                onChange={(e) => {setCreatedAt((e.target.value))}}/>
      </TagInfoWrapper>

      <TagInfoWrapper>
        <Editor label="备注" type="text" placeholder="请输入备注"
                value={notes} onChange={(e) => {setNotes(e.target.value);}}/>
      </TagInfoWrapper>

      <ButtonList>
        <SaveButton onClick={onSave} disabled={cantSave()}>保存修改</SaveButton>
        <DeleteButton onClick={onDelete}>删除记录</DeleteButton>
      </ButtonList>
    </>
  );

};

export {RecordContent};